
window.onload = function(){
    if(-1 < navigator.platform.indexOf("Win")
    || -1 < navigator.platform.indexOf("Mac")
    ) {
        let pcStyle = document.createElement("style");
        pcStyle.innerText = `
        body{
            background-color: #1e1e1e;
        }
        .js:hover{
            background-color: #e3722e;
            box-shadow: 10px 10px 10px #888888;
            transition: background-color .1s, box-shadow .5s;
        }
        .js:active{
            color: springgreen;
            transition: color .5s;
        }
        `;
        document.head.appendChild(pcStyle);
        autojs = function () {
            return "当前是pc环境！";
        }
    }
    loadView(code)
    refreshView()
}


function runjs(index){
    console.log(index)
    if(typeof code[index].code == "string")
        return autojs(code[index].code)
    return false;
}

function autojs(code, mode) {
    if(!autojsDownloadTagA) {
        // 创建a标签
        var autojsDownloadTagA = document.createElement('a');
        autojsDownloadTagA.download = "要执行的代码.js";
        autojsDownloadTagA.style.display = 'none';
        document.body.appendChild(autojsDownloadTagA);
    }
    /*
        //生成一个blob二进制数据，内容为json数据
        var blob;
        console.log("===")
        if(mode=="engine") new Blob([code],{type: "auto/JS;charset=utf-8"});
        else new Blob([code],{type: "auto/js;charset=utf-8"});
        //生成一个指向blob的URL地址，并赋值给a标签的href属性
        autojsDownloadTagA.href = URL.createObjectURL(blob);
        autojsDownloadTagA.click();
    */
    autojsDownloadTagA.href = "data:auto/js;charset=utf-8,\ncode:"+code.replace(/\\/g,"\\\\");
    return autojsDownloadTagA.click();
}

/**
 * 加载视图
 * [{
        title: "代码名字",
        version: "版本1.0",
        author: "作者",
        body: "具体代码",
        describe: "功能描述"
    }]
 * @param {Array} data 指定格式的数据数组集合[{},{}]
 * @param {String} template 模板将会替换这些数据 "{{index}}" "{{title}}" "{{version}}" "{{author}}" "{{describe}}"
 */
function loadView(data, template) {
    let oIndex = document.querySelector("#app");
    // 如果不存在index元素或不存在appendChild方法则跳出
    if(!oIndex || typeof oIndex.appendChild != "function") return false;
    template = template || `<div class="js" onclick="runjs({{index}})"><div class="title">{{title}}</div><div class="info">{{author}} -- {{version}}</div><div class="describe">{{describe}}</div></div>`;
    for (let i = 0; i < data.length; i++) {
        let t = template;
        let e = data[i];
        data[i].code = data[i].code.replace(/\\/g,"\\\\")
        t = t.replace(/{{index}}/g, i);
        t = t.replace(/{{title}}/g, e.title || e.t);
        t = t.replace(/{{version}}/g, e.version || e.v);
        t = t.replace(/{{author}}/g, e.author || e.a);
        t = t.replace(/{{describe}}/g, e.describe || e.d);
        // 创建按钮元素
        oIndex.innerHTML += t;
    }
}

/**
 * 刷新视图，统一按钮布局
 */
function refreshView() {
    let divs = document.querySelectorAll("#app>*");
    // 获取到所有的长度
    let lens={};
    let s = "_";
    divs.forEach(e=>{
        try{
            // 34_64
            // e = parseInt(e.offsetWidth*0.8)+s+parseInt(e.offsetHeight*0.8);
            e = parseInt(e.offsetWidth)+s+parseInt(e.offsetHeight);
            // e = parseInt(e.width)+s+parseInt(e.height);
            if(typeof lens[e] != "number") lens[e] = 0;
            lens[e] ++;
        }catch(error){
            console.log("出现异常", error)
        }
    })
    console.log(lens)
    // 获取到长度相等的最多的一个长度
    let maxLength = 0;
    // 1_1
    let lenStr = "1"+s+"1";
    for (const key in lens) {
        if(maxLength < lens[key]) {
            maxLength = lens[key];
            lenStr = key;
        }
    }
    
    // 将获取到的这个长度设置到所有按钮元素中
    // 将 34_64 拆成 [34,64]，分别对应宽，高，但是不需要使用高度
    lenStr = lenStr.split(s);
    try{
        let style = getCss("main.css", ".js").style;
        style.width = lenStr[0]+"px";
        style.height = lenStr[1]+"px";
    }catch(err){
        console.log(err);
        // 本地读取css时会报错 SecurityError: Failed to read the 'rules' property from CSSStyleSheet': Cannet access rules
        // document.body.innerHTML+="<br>"+err;
        let newCss = document.querySelector("#newCss")||document.createElement("style");
        newCss.innerText = '.js{width: '+lenStr[0]+'px; height: '+lenStr[1]+'px;}';
        document.head.appendChild(newCss);
    }
}

/**
 * 通过文件名和选择器名来选择css对象
 * 需要将css的选择器写标准，不适用于手机本地加载
 */
function getCss(fileName,selectorName, debug) {
    let ss = document.styleSheets;
    let temp = [];
    let i = 0;

    // 通过文件名获取到下标
    for (; i < ss.length; i++) {
        let h = ss[i].href;
        h = h.substring(h.lastIndexOf("/")+1);
        temp.push(h)
        if(h == fileName){
            break;
        }
    }
    if(debug) console.log("所有css文件名字：", temp);
    
    let rs = ss[i].rules;
    let j = 0;
    temp = [];
    // 通过名字拿到样式
    for (; j < rs.length; j++) {
        let r = rs[j].selectorText;
        temp.push(r)
        if(r == selectorName){
            break;
        }
    }
    if(debug) console.log("所有选择器名字：", temp)
    return rs[j];
}